package com.seata.demo.order.service.impl;

import com.seata.demo.order.entity.Order;
import com.seata.demo.order.feign.AccountFeignClient;
import com.seata.demo.order.feign.StorageFeignClient;
import com.seata.demo.order.mapper.OrderMapper;
import com.seata.demo.order.service.OrderService;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private StorageFeignClient storageFeignClient;

    @Autowired
    private AccountFeignClient accountFeignClient;

    @Override
    @GlobalTransactional(name = "create-order-at", rollbackFor = Exception.class)
    public void createOrder(String userId, String commodityCode, Integer count) {
        // 1. 创建订单
        Order order = new Order();
        order.setUserId(userId);
        order.setCommodityCode(commodityCode);
        order.setCount(count);
        BigDecimal price = new BigDecimal(100); // 假设单价100元
        order.setMoney(price.multiply(new BigDecimal(count)));
        order.setStatus(0); // 0-创建中
        orderMapper.insert(order);

        // 2. 扣减库存
        storageFeignClient.deduct(commodityCode, count);

        // 3. 扣减账户余额
        accountFeignClient.debit(userId, order.getMoney());

        // 4. 更新订单状态为已完成
        orderMapper.updateStatus(order.getId(), 1);
        
        // 测试回滚，取消注释即可
//         if (true) {
//             throw new RuntimeException("模拟异常，测试AT事务回滚");
//         }
    }
}
